<?php
class ApartmentsController extends AppController {

	var $name = 'Apartments';
	var $helpers = array('Html', 'Form' );
	var $uses = array('Semester', 'Language', 'Apartment', 'Assignment');

	function admin_index() {
		$this->redirect('/admin/semesters');
	}

	function admin_list($semesterId = null) {
		if ($semesterId == null) {
			$this->redirect('/admin/semesters');
		}
		$this->set('semesterId', $semesterId);
		$this->Apartment->recursive = 2;
		$this->set('apartments', $this->Apartment->findAllBySemesterId($semesterId));
		$this->set('semester', $this->Semester->findBySemesterId($semesterId));
	}

	function admin_add($semesterId = null) {
		if ($semesterId == null) {
			$this->redirect('/admin/semesters');
			return;
		}
		$this->set('semesterId', $semesterId);
		$this->set('languageList', $this->Language->getLanguageList());
		$this->set('genderList', array('Male' => 'Male', 'Female' => 'Female'));
		$this->set('semester', $this->Semester->findBySemesterId($semesterId));
		if (empty($this->data)) {
			$this->render();
		} else {
			$this->cleanUpFields();
			$this->data['Apartment']['semester_id'] = $semesterId;
			if ($this->Apartment->save($this->data)) {
				$this->Session->setFlash('The Apartment has been saved');
				$this->redirect('/admin/apartments/list/'.$semesterId);
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function admin_edit($id = null) {
		$this->set('semesterList', $this->Semester->getSemesterList());
		$this->set('languageList', $this->Language->getLanguageList());
		$this->set('genderList', array('Male' => 'Male', 'Female' => 'Female'));
		if (empty($this->data)) {
			$genders = array("Men" => "Men", "Women" => "Women");
			if (!$id) {
				$this->Session->setFlash('Invalid id for Apartment');
				$this->redirect('/admin/apartments/list/');
			}
			$this->data = $this->Apartment->read(null, $id);
		} else {
			$this->cleanUpFields();
			if ($this->Apartment->save($this->data)) {
				$semesterId = $this->data['Apartment']['semester_id'];
				$this->Session->setFlash('The Apartment has been saved');
				$this->redirect('/admin/apartments/list/'.$semesterId);
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function admin_delete($semesterId = null, $apartmentId = null) {
		if ($apartmentId == null) {
			$this->redirect('admin/semesters/'.$semesterId);
		}

		$this->Apartment->del($apartmentId);
		$this->Assignment->recursive = 0;
		$assignments = $this->Assignment->findAllByApartmentId($apartmentId);
		foreach ($assignments as $assignment) {
			$assignmentId = $assignment['Assignment']['assignment_id'];
			$this->Assignment->del($assignmentId);
		}
		$this->redirect('admin/apartments/list/'.$semesterId);
	}
}
?>
